package com.lipuwater.agent.ble.http;

import android.app.Activity;
import android.content.Context;
import android.widget.Toast;

import com.ismartlib.utils.NetUtils;
import com.lipuwater.agent.R;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsDevice;
import com.lipuwater.agent.utils.link.ErrorInterface;
import com.lipuwater.agent.utils.link.LinkCallTask;
import com.lipuwater.agent.utils.link.NextInterface;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃永无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * Created by  Administrator  on 2017/1/16.
 * Email:924686754@qq.com
 * 设备激活，与服务器交互，交互流程包括提交设备
 * Post 时间标识、协议版本、mcu序列号、mac
 * Get  主板编码、剩余天数
 */
public class DeviceActivateHttp {

    private Context mContext;
    private String token;
    private String mTimeId, mVersion, mMcu, mMac, mProductCode, mDeviceName;
    private CallBack mCallBack;
    private int deviceId = 0;
    private LinkCallTask mLinkCallTask;

    public DeviceActivateHttp(Context mContext, String token) {
        this.mContext = mContext;
        this.token = token;
        mLinkCallTask = new LinkCallTask();
    }

    public DeviceActivateHttp setParams(String timeId, String version, String mcu, String mac, String productCode, String deviceName) {
        this.mTimeId = timeId;
        this.mVersion = version;
        this.mMcu = mcu;
        this.mMac = mac;
        this.mProductCode = productCode;
        this.mDeviceName = deviceName;
        steps();
        return this;
    }

    public DeviceActivateHttp setCallBack(CallBack callBack) {
        this.mCallBack = callBack;
        return this;
    }

    public void unCallBack() {
        this.mCallBack = null;
        this.mContext = null;
    }

    public DeviceActivateHttp getMainCode() {
        mLinkCallTask.toStart();
        return this;
    }

    private void steps() {
        mLinkCallTask.setNext(new NextInterface() {
            @Override
            public void onNext(Object object) {
                /**
                 * 提交设备基础信息
                 */
                Map<String, Object> params = new HashMap<>();
                params.put("token", token);
                params.put("timeId", mTimeId);
                params.put("version", mVersion);
                params.put("macId", mMac);
                params.put("code", mProductCode);
                params.put("deviceName", mDeviceName);
                ApiRequestsDevice.PostBleBasisData(mContext, params, new ApiCallBack() {
                    @Override
                    public void onResponse(ResponseParams result) {
                        if (result.getStatus() == HttpConfig.success) {
                            double deviceIdDou = (Double) result.getParams().get("deviceId");
                            deviceId = (int) Math.round(deviceIdDou);
                            mLinkCallTask.toNext();
                        } else {
                            mLinkCallTask.toError(result.getMessage());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        if (!NetUtils.isConnected(mContext)) {
                            mLinkCallTask.toError(mContext.getString(R.string.network_fails));
                        } else {
                            mLinkCallTask.toError(mContext.getString(R.string.service_error));
                        }
                    }
                });
            }
        }, new NextInterface() {
            @Override
            public void onNext(Object object) {
                /**
                 * 提交设备MCU
                 */
                Map<String, Object> params = new HashMap<>();
                params.put("token", token);
                params.put("deviceId", deviceId);
                params.put("mcuId", mMcu);
                ApiRequestsDevice.PostBleMcuOrMainCode(mContext, params, new ApiCallBack() {
                    @Override
                    public void onResponse(ResponseParams result) {
                        if (result.getStatus() == HttpConfig.success) {
                            mLinkCallTask.toNext();
                        } else {
                            mLinkCallTask.toError(result.getMessage());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        if (!NetUtils.isConnected(mContext)) {
                            mLinkCallTask.toError(mContext.getString(R.string.network_fails));
                        } else {
                            mLinkCallTask.toError(mContext.getString(R.string.service_error));
                        }
                    }
                });
            }
        }, new NextInterface() {
            @Override
            public void onNext(Object object) {
                /**
                 * 获取设备主板编码
                 */
                Map<String, Object> params = new HashMap<>();
                params.put("token", token);
                params.put("deviceId", deviceId);
                ApiRequestsDevice.getBleMainCode(mContext, params, new ApiCallBack() {
                    @Override
                    public void onResponse(ResponseParams result) {
                        if (result.getStatus() == HttpConfig.success) {
                            String mainCode = (String) result.getParams().get("deviceMainCode");
                            if (mCallBack != null && mainCode != null) {
                                mCallBack.onServiceData(mainCode, "", deviceId, false);
                            }
                        } else {
                            mLinkCallTask.toError(result.getMessage());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        if (!NetUtils.isConnected(mContext)) {
                            mLinkCallTask.toError(mContext.getString(R.string.network_fails));
                        } else {
                            mLinkCallTask.toError(mContext.getString(R.string.service_error));
                        }
                    }
                });
            }
        }).setError(new ErrorInterface() {
            @Override
            public void onError(Object object) {
                String error = object.toString();
                Toast.makeText(mContext, error, Toast.LENGTH_SHORT).show();
                Activity activity = (Activity) mContext;
                activity.finish();
                unCallBack();
            }
        });
    }

    /**
     * 确认激活
     */
    public void ConfirmActivate(int orderId, int installType) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("deviceId", deviceId);
        params.put("orderId", orderId);
        params.put("type", installType + "");
        ApiRequestsDevice.ConfirmActivate(mContext, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    if (mCallBack != null) {
                        mCallBack.onServiceData("", "", deviceId, true);
                    }
                } else {
                    mLinkCallTask.toError(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (!NetUtils.isConnected(mContext)) {
                    mLinkCallTask.toError(mContext.getString(R.string.network_fails));
                } else {
                    mLinkCallTask.toError(mContext.getString(R.string.service_error));
                }
            }
        });
    }

    /**
     * 获取剩余天数充值指令
     */
    public void getRechargedays() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("deviceId", deviceId);
        params.put("timeId", mTimeId);
        ApiRequestsDevice.getRechargedays(mContext, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    String deviceDay = (String) result.getParams().get("deviceDay");
                    if (mCallBack != null && deviceDay != null) {
                        mCallBack.onServiceData("", deviceDay, deviceId, false);
                    }
                } else {
                    mLinkCallTask.toError(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (!NetUtils.isConnected(mContext)) {
                    mLinkCallTask.toError(mContext.getString(R.string.network_fails));
                } else {
                    mLinkCallTask.toError(mContext.getString(R.string.service_error));
                }
            }
        });
    }


    public interface CallBack {
        void onServiceData(String mainCode, String days, int deviceId, boolean confirmActivate);
    }
}
